package com.base.common.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.operamasks.faces.annotation.Convert;
import org.operamasks.faces.annotation.DefineConverter;
import org.operamasks.faces.annotation.Format;

import com.base.commons.SpringBeanHolder;
import com.base.security.dao.ISecurityUserDao;
import com.base.security.entity.SecurityUser;

/**
 * 用于将用户username转换成用户姓名的转换类
 * 
 * 
 */
@DefineConverter(id = "userFullnameFormatter")
public class UserFullnameConverter implements Converter {
	private final static Log logger = LogFactory
			.getLog(UserFullnameConverter.class);
	private ISecurityUserDao userDao = SpringBeanHolder
			.getBean("securityUserDao");

	@Format
	public String format(Object value) {
		logger.debug("user value:" + value);
		if (value == null || "".equals(value.toString()))
			return "";
		String userName = value.toString();
		String[] temp = userName.split(",");
		List<String> userNames = new ArrayList<String>(temp.length);
		for (String ss : temp) {
			userNames.add(ss);
		}
		ISecurityUserDao userDao = SpringBeanHolder.getBean("securityUserDao");
		List<SecurityUser> users = userDao.getAll();
		if (users.isEmpty())
			return userName;
		StringBuilder sb = new StringBuilder();
		for (SecurityUser su : users) {
			if (userNames.contains(su.getUsername())) {
				sb.append(su.getFullname());
				sb.append(",");
			}
		}
		return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : value
				.toString();
	}

	@Convert
	public Object convert(String value) {
		return null;
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		logger.debug("user value:" + value);
		if (value == null || "".equals(value.toString()))
			return "";
		String userName = value.toString();
		String[] temp = userName.split(",");
		List<String> userNames = new ArrayList<String>(temp.length);
		for (String ss : temp) {
			userNames.add(ss);
		}
		ISecurityUserDao userDao = SpringBeanHolder.getBean("securityUserDao");
		List<SecurityUser> users = userDao.getAll();
		if (users.isEmpty())
			return userName;
		StringBuilder sb = new StringBuilder();
		for (SecurityUser su : users) {
			if (userNames.contains(su.getUsername())) {
				sb.append(su.getFullname());
				sb.append(",");
			}
		}
		return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : value
				.toString();
	}
}
